const setHeader = () => {
	try {
		let token = uni.getStorageSync('POOL_TOKEN')
		let header = {
			'x-app-token': token,
			'Content-Type': 'application/json',
		}
		return header
	} catch (e) {
		//TODO handle the exception
	}
}


//响应拦截器
const responseInterceptor = (res) =>{
	let flag = true
	switch (res.code){
		case 200:
		console.log('in 1')
		    flag = true
			break;
		case 401:
		console.log('in 2')
			flag = false
			uni.showToast({
				title: res.data,
				icon:'none'
			});
			uni.removeStorageSync('POOL_TOKEN')
			setTimeout(()=>{
				uni.reLaunch({
					url:'/pages/login/index'
				})
			},200)
			break;
		default:
		console.log('in 3')
		    uni.showModal({
		    	title: '提示',
		    	content: res.data || '系统出错，请重试',
		    	success: res => {
					flag = false
				},
		    });
			break;
	}
	return flag
}






//请求参数配置
const config = {
	baseUrl: "http://192.168.3.116:3000",
}








//请求数据传入
const http = (data) => {
	data.url = config.baseUrl + data.url
	let newRequestData = Object.assign(config, data)
	newRequestData['header'] = setHeader()
	return req(newRequestData)
}

const req = (requestData,headers) => {
	return new Promise((resolve, reject) => {
		uni.request({
			url: requestData.url,
			data: requestData.data || {},
			method: requestData.method,
			header:requestData.header,
			success: (res) => {
				if(responseInterceptor(res.data)){
					resolve(res.data)
				}
				console.log(`请求url:${requestData.url}`)
				console.log(`请求参数:${JSON.stringify(requestData.data)},${JSON.stringify(requestData.method)}`)
				console.log(`请求响应：${JSON.stringify(res)}`)
			},
			fail: (err => {
				reject(err)
				console.log(`请求url:${requestData.url}`)
				console.log(`请求参数:${JSON.stringify(requestData.data)}`)
				console.log(`请求响应：${JSON.stringify(err)}`)
			})
		})
	})
}










module.exports = http
